package com.hbxx.lotteryapp.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbxx.lotteryapp.commons.Result;
import com.hbxx.lotteryapp.commons.TokenService;
import com.hbxx.lotteryapp.entity.LoginUser;
import com.hbxx.lotteryapp.entity.WXAuth;
import com.hbxx.lotteryapp.entity.WxUser;
import com.hbxx.lotteryapp.mapper.WxUserMapper;
import com.hbxx.lotteryapp.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author crush
 * @since 2021-09-14
 */
@Slf4j
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements IWxUserService {


    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    @Resource
    private TokenService tokenService;
    @Resource
    private WxUserMapper wxUserMapper;

    /**
     * 微信小程序登录凭证校验
     *
     * @param code
     * @return
     */
    @Override
    public Result authLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(replaceUrl);
        log.info("发送链接后获得的数据{}", res);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");
        if (StringUtils.isNotBlank(openid)) {
            //用户信息是否存在，存在直接返回登录态，
            QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
            wrapper.eq("open_id",openid);
            WxUser wxUser = wxUserMapper.selectOne(wrapper);
            WxUser wxUser1 = null;
            if(wxUser == null){
                // 若不存在即添加进数据库，做持久化。根据自己需求 更改
                wxUser1 = new WxUser();
                wxUser1.setOpenId(openid);
                wxUser1.setIsAuth(1);
                wxUser1.setUnionId(jsonObject.getString("unionid"));
                int insert = wxUserMapper.insert(wxUser1);
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setOpenId(wxUser1.getOpenId());
            String token = tokenService.createToken(loginUser);
            WXAuth wxAuth = new WXAuth();
            wxAuth.setOpenid(openid);
            wxAuth.setToken(token);
            return Result.SUCCESS(wxAuth);
        }
        return Result.FAIL("登录凭证有误");
    }

    /**
     * 获取登录用户信息
     * @param request
     * @return
     */
    @Override
    public Result userInfo(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        String openId = loginUser.getOpenId();
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id",openId);
        WxUser wxUser = wxUserMapper.selectOne(wrapper);
        return Result.SUCCESS(wxUser);
    }

}